package com.mxq.eclipse.mqtt.demo.publish.service.impl;


import com.mxq.eclipse.mqtt.demo.publish.MqttPublishDto;
import com.mxq.eclipse.mqtt.demo.publish.PublishConnect;
import com.mxq.eclipse.mqtt.demo.publish.service.MqttPublishService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author xiaoqiang
 * @date 2020-05-09 17:36
 */
@Slf4j
@Service
public class MqttPublishServiceImpl implements MqttPublishService {

    @Autowired
    private PublishConnect publishConnect;

    @Override
    public Boolean publishOrigin(MqttPublishDto mqttPublishDto) {
        log.info("进入【MqttServiceImpl】的[publishOrigin]方法,入参：{}",mqttPublishDto);
        try {
            // 内存存储
            MemoryPersistence persistence = new MemoryPersistence();
            // 创建客户端
            MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
            mqttConnectOptions.setUserName(mqttPublishDto.getUserName());
            mqttConnectOptions.setPassword(mqttPublishDto.getPassword().toCharArray());
            MqttClient sampleClient = publishConnect.connectMqttClient(mqttPublishDto, mqttConnectOptions);
            // 创建消息
            log.info("【MQTT】发布的消息：{}", mqttPublishDto.getMessage());
            MqttMessage message = new MqttMessage(mqttPublishDto.getMessage().getBytes());
            // 设置消息的服务质量
            Integer qos = mqttPublishDto.getQos() == null ? 1: mqttPublishDto.getQos();
            message.setQos(qos);
            log.info("【MQTT_TOPIC】:{}",mqttPublishDto.getTopic());
            sampleClient.publish(mqttPublishDto.getTopic(), message);
            // 断开连接
            sampleClient.disconnect();
            // 关闭客户端
            sampleClient.close();
            log.info("【MQTT】发布的消息<成功>");
            return true;
        } catch (MqttException me) {
            log.error("reasonCode:{},msg:{},loc:{},cause:{}",me.getReasonCode(),me.getMessage(),me.getLocalizedMessage(),me.getCause());
            me.printStackTrace();
            return false;
        }
    }
}
